function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
/*
 * @Author: hc
 * @Date: 2024-03-06 19:45:42
 * @LastEditTime: 2024-03-07 17:53:59
 * @LastEditors: hc
 * @Description:
 */
import { DeleteOutlined, PlusSquareOutlined } from '@ant-design/icons';
import { Radio } from 'antd';
import { iup } from "../../../../util";
import { ROW_PERMISSION_RELATION, ROW_PERMISSION_RELATION_TEXT } from "../../types";
import "./index.less";

// 行高
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var ITEM_HEIGHT = 32;

// 间距
var MARGIN = 16;

// 存储对象节点的高度/线条高度等信息
var weakMap = new WeakMap();
export var RulesController = function RulesController(props) {
  var value = props.value,
    disabled = props.disabled,
    maxLevel = props.maxLevel,
    maxSize = props.maxSize,
    component = props.component,
    onAddCondition = props.onAddCondition,
    onDeleteCondition = props.onDeleteCondition,
    onChangeCondition = props.onChangeCondition,
    onChangeRowValues = props.onChangeRowValues;

  /**
   * 是否为条件节点
   */
  var isCondition = function isCondition(item) {
    return (item === null || item === void 0 ? void 0 : item.type) && [ROW_PERMISSION_RELATION.AND, ROW_PERMISSION_RELATION.OR].includes(item === null || item === void 0 ? void 0 : item.type);
  };

  /**
   * 计算每个节点的高度(height)/线条高度(lineHeight)/距离底部高度(bottom)
   */
  var calculateTreeItemHeight = function calculateTreeItemHeight(item, disabled) {
    var composeDisabled = disabled || !!item.disabled;
    if (!(item !== null && item !== void 0 && item.children)) return weakMap.set(item, {
      height: ITEM_HEIGHT + MARGIN,
      lineHeight: ITEM_HEIGHT
    });
    item.children.map(function (child) {
      return calculateTreeItemHeight(child, composeDisabled);
    });
    var isLastCondition = !item.children.some(isCondition);
    var firstNodeIsCondition = isCondition(item.children[0]);
    // 编辑模式下计算
    if (!composeDisabled) {
      var height = item.children.reduce(function (prev, curr) {
        return prev + weakMap.get(curr).height;
      }, ITEM_HEIGHT);
      var lineHeight;
      // 如果当前节点是最后的判断节点
      if (isLastCondition) {
        var firstNodeLineHeight = weakMap.get(item.children[0]).height - MARGIN;
        var lastNodeHeight = ITEM_HEIGHT;
        lineHeight = height - firstNodeLineHeight / 2 - lastNodeHeight / 2;
      } else {
        var _item$children;
        var _firstNodeLineHeight = firstNodeIsCondition ? weakMap.get(item.children[0]).lineHeight / 2 + ITEM_HEIGHT / 2 : ITEM_HEIGHT / 2 + MARGIN;
        lineHeight = _firstNodeLineHeight + ((_item$children = item.children) === null || _item$children === void 0 ? void 0 : _item$children.slice(1).reduce(function (prev, curr) {
          return prev + weakMap.get(curr).height;
        }, ITEM_HEIGHT / 2));
      }
      weakMap.set(item, {
        height: height,
        lineHeight: lineHeight
      });
    } else {
      var _height = item.children.reduce(function (prev, curr) {
        return prev + weakMap.get(curr).height;
      }, 0);
      var _lineHeight;
      var bottom;
      // 如果当前节点是最后的判断节点
      if (isLastCondition) {
        _lineHeight = _height - ITEM_HEIGHT - MARGIN;
      } else {
        var _item$children2;
        var firstNode = item.children[0];
        var lastNode = item.children[item.children.length - 1];
        var _firstNodeLineHeight2 = weakMap.get(firstNode).height - getNodeReduceHeight(item, true);
        var lastNodeIsCondition = isCondition(lastNode);
        var reduceLastHeight = getNodeReduceHeight(item, false);
        var lastNodeLineHeight = weakMap.get(lastNode).height - MARGIN - reduceLastHeight;
        bottom = lastNodeIsCondition ? reduceLastHeight : ITEM_HEIGHT / 2;
        _lineHeight = _firstNodeLineHeight2 + ((_item$children2 = item.children) === null || _item$children2 === void 0 ? void 0 : _item$children2.slice(1, -1).reduce(function (prev, curr) {
          return prev + weakMap.get(curr).height;
        }, 0)) + lastNodeLineHeight;
      }
      weakMap.set(item, {
        bottom: bottom,
        lineHeight: _lineHeight,
        height: _height
      });
    }
    return item;
  };

  /**
   * 获取节点高度
   */
  var getNodeReduceHeight = function getNodeReduceHeight(item, isFirst) {
    var _item$children3, _item$children4, _item$children5;
    var currentNode = isFirst ? item === null || item === void 0 || (_item$children3 = item.children) === null || _item$children3 === void 0 ? void 0 : _item$children3[0] : item === null || item === void 0 || (_item$children4 = item.children) === null || _item$children4 === void 0 ? void 0 : _item$children4[(item === null || item === void 0 || (_item$children5 = item.children) === null || _item$children5 === void 0 ? void 0 : _item$children5.length) - 1];
    if (!currentNode) return ITEM_HEIGHT / 2;
    var currentNodeIsCondition = isCondition(currentNode);
    if (currentNodeIsCondition) {
      var _weakMap$get;
      return ((_weakMap$get = weakMap.get(currentNode)) === null || _weakMap$get === void 0 ? void 0 : _weakMap$get.lineHeight) / 2 + getNodeReduceHeight(currentNode, isFirst);
    }
    return ITEM_HEIGHT / 2;
  };

  /**
   * 条件渲染
   */
  var renderCondition = function renderCondition(item, namePath, disabled) {
    var _item$children6;
    var composeDisabled = disabled || !!item.disabled;

    // 渲染条件节点和线条
    if (item !== null && item !== void 0 && (_item$children6 = item.children) !== null && _item$children6 !== void 0 && _item$children6.length) {
      var _item$children7;
      var childrenPath = function childrenPath(index) {
        var newPath = _toConsumableArray(namePath);
        newPath.push.apply(newPath, ['children', index]);
        return newPath;
      };
      var _weakMap$get2 = weakMap.get(item),
        lineHeight = _weakMap$get2.lineHeight,
        bottom = _weakMap$get2.bottom;
      return /*#__PURE__*/_jsxs("div", {
        className: iup.classNames('ruleController__condition', {
          'ruleController__condition--active': item.children.length > 1
        }),
        children: [/*#__PURE__*/_jsxs("div", {
          className: iup.classNames('condition__box', {
            disabled: composeDisabled
          }),
          style: {
            height: lineHeight,
            bottom: bottom !== null && bottom !== void 0 ? bottom : MARGIN
          },
          children: [/*#__PURE__*/_jsxs(Radio.Group, {
            size: "small",
            className: "condition__box--radio",
            value: item === null || item === void 0 ? void 0 : item.type,
            buttonStyle: "solid",
            onChange: function onChange(e) {
              return !composeDisabled && onChangeCondition(item.key, item === null || item === void 0 ? void 0 : item.type);
            },
            children: [/*#__PURE__*/_jsx(Radio.Button, {
              value: ROW_PERMISSION_RELATION['AND'],
              children: ROW_PERMISSION_RELATION_TEXT[ROW_PERMISSION_RELATION.AND]
            }), /*#__PURE__*/_jsx(Radio.Button, {
              value: ROW_PERMISSION_RELATION['OR'],
              children: ROW_PERMISSION_RELATION_TEXT[ROW_PERMISSION_RELATION.OR]
            })]
          }), item.children.length > 1 && /*#__PURE__*/_jsx("span", {
            className: iup.classNames('condition__box--line', {
              disabled: disabled
            })
          })]
        }), item.children.map(function (d, index) {
          return renderCondition(d, childrenPath(index), composeDisabled);
        }), !composeDisabled && /*#__PURE__*/_jsxs("div", {
          className: "condition__add",
          children: [/*#__PURE__*/_jsx("span", {
            className: "condition__add--line"
          }), /*#__PURE__*/_jsx("span", {
            className: iup.classNames('condition__add--icon', (item === null || item === void 0 || (_item$children7 = item.children) === null || _item$children7 === void 0 ? void 0 : _item$children7.length) >= maxSize ? 'condition__add--icon--disabled' : ''),
            onClick: function onClick() {
              if (item !== null && item !== void 0 && item.children && item.children.length >= maxSize) return;
              onAddCondition({
                key: item.key,
                isOut: true
              });
            },
            children: "\u65B0\u589E\u6761\u4EF6\u7EC4"
          })]
        })]
      }, item.key);
    }
    // 渲染自定义的 component
    return /*#__PURE__*/_jsxs("div", {
      className: "ruleController__item",
      children: [(value === null || value === void 0 ? void 0 : value.children) && /*#__PURE__*/_jsx("span", {
        className: iup.classNames('ruleController__item--line', {
          disabled: disabled
        })
      }), /*#__PURE__*/_jsx("div", {
        className: "ruleController__item--component",
        children: component({
          rowKey: item.key,
          disabled: composeDisabled,
          name: [].concat(_toConsumableArray(namePath), ['rowValues']),
          rowValues: item.rowValues,
          onChange: onChangeRowValues
        })
      }), !composeDisabled && /*#__PURE__*/_jsxs("div", {
        className: "ruleController__item--operation",
        children: [/*#__PURE__*/_jsx(DeleteOutlined, {
          className: "icon",
          onClick: function onClick() {
            return onDeleteCondition(item.key);
          }
        }), item.level === maxLevel ? null : /*#__PURE__*/_jsx(PlusSquareOutlined, {
          className: "icon",
          onClick: function onClick() {
            return onAddCondition({
              key: item.key
            });
          }
        })]
      })]
    }, item.key);
  };
  if (!value) return null;
  calculateTreeItemHeight(value, !!disabled);
  return /*#__PURE__*/_jsx("div", {
    className: "ruleController",
    children: renderCondition(value, [], !!disabled || !!value.disabled)
  });
};